package com.news.cloud.service;

import com.news.cloud.exception.InvalidEmailException;
import com.news.cloud.exception.InvalidItemException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.core.env.PropertyResolver;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hiephn on 2014/07/23.
 */
public abstract class AbstractService{

    @Resource(name = "mnpPropertyResolver")
    protected PropertyResolver mnpProperties;

    protected String wildcardSearchKey(String key) {
        return StringUtils.isEmpty(key) ? "%" : "%" + key + "%";
    }

    protected RestTemplate restTemplate = new RestTemplate();

    /**
     * Standardize the phone number into +84xxxx...
     * If the the phone is already in the format. It will be leaved unchanged.
     *
     * @param phone
     * @return
     * @throws InvalidItemException when the format of the phone is not recognized
     */
    protected String standardizePhone(String phone) throws InvalidItemException {
        final String PREFIX = mnpProperties.getProperty("phone.default-prefix", "+84");
        String standardPhone;
        if (StringUtils.startsWith(phone, "0")) {
            standardPhone = PREFIX + StringUtils.substring(phone, 1);
        } else if (StringUtils.isNumeric(String.valueOf(phone.charAt(0)))) {
            standardPhone = PREFIX + phone;
        } else if (StringUtils.startsWith(phone, "+")) {
            standardPhone = phone;
        } else {
            throw new InvalidItemException("Phone number is invalid: " + phone);
        }
        return standardPhone;
    }

    protected void validateEmailFormat(String email) throws InvalidEmailException {
        try {
            new InternetAddress(email);
        } catch (AddressException e) {
            throw new InvalidEmailException("Invalid email address: " + email);
        }
    }

    protected boolean isNotEmpty(String str) {
        return StringUtils.isNotEmpty(str);
    }

    protected boolean isEmpty(String str) {
        return StringUtils.isEmpty(str);
    }
}
